import { defineStore } from 'pinia'
import { getCartData, deleGoods, changeGoodsNum } from '@/api/index.js'
import { reactive } from 'vue'
export const useCartStore = defineStore('shopping-cart', {
    state: () => {
        return {
            itemInCartData: [],

            checkedGoodsId:[],//选中要结算的商品的id
        }
    },
    actions: {
        // 给每个购物车中的数据添加checked属性
        changeCartData(list) {
            this.itemInCartData = list.map(item => {
                item.checked = true;
                return item

            })
        },
        // 获取购物车数据
        GetCartData() {
            getCartData().then(res => {
                if (res.resultCode == 200) {
                    this.changeCartData(res.data || [])
                }
            })
        },
        // 全选按钮
        toggleAll(flag) {
            this.itemInCartData.forEach(item => item.checked = !flag)
        },
        // 删除商品
        deleteBtn(id) {
            let checkedList = [];
            this.itemInCartData.forEach(item => {
                if (item.cartItemId != id) {
                    checkedList.push({ id: item.cartItemId, isChecked: item.checked })
                }
            })

            deleGoods(id).then(res => {
                if (res.resultCode == 200) {
                    getCartData().then(data => {
                        if (data.resultCode == 200) {
                            this.changeCartData(data.data || [])
                        }
                    })
                }
            })

        },
        // 步进器发生变化
        goodsNumChange(data) {
            changeGoodsNum(data).then(res => {
                
            })
        },

        // 把选中的商品的id赋给checkedGoodsId
        checkedGoods() {
            
            this.checkedGoodsId.splice(0, this.checkedGoodsId.length)
            
            this.itemInCartData.filter(item => {
                if (item.checked == true) {
                    this.checkedGoodsId.push(item.cartItemId)
                }
            })
        }

    },
    getters: {
        // 计算购物车中的物品数量
        itemNumInCart() {
            return this.itemInCartData.reduce((prev, next) => {
                return prev + next.goodsCount;
            }, 0)
        },
        // 判断是否全选
        isAllChecked() {
            if (this.itemInCartData.length == 0) {
                return false
            } else {
                return this.itemInCartData.every(item => item.checked == true)
            }
            
        },
        // 计算合计金额
        totalPrice() {
            // return this.itemInCartData.reduce((prev, next) => {

            //     return prev + (next.goodsCount * next.sellingPrice);
            // }, 0)
            let sum = 0;
            this.itemInCartData.forEach(item => {
                if (item.checked) {
                    sum += item.sellingPrice * item.goodsCount
                }
            })
            return sum
        }

    }
})